package com.health.db.service.sm.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.db.dao.sm.IGoodsDataDao;
import com.health.db.dao.sm.IGoodsListDao;
import com.health.db.dao.sm.IGoodsOrderDao;
import com.health.db.dao.user.IGoodsDataStuffRemarkDao;
import com.health.db.dao.user.IGoodsDataUserDao;
import com.health.db.dao.user.IUserAccountJournalDao;
import com.health.db.dao.user.IUserAccountLedgerDao;
import com.health.db.dao.user.IUserCardListDao;
import com.health.db.dao.user.IUserLISTDao;
import com.health.db.model.GoodsData;
import com.health.db.model.GoodsDataExample;
import com.health.db.model.GoodsDataStuffRemark;
import com.health.db.model.GoodsDataUser;
import com.health.db.model.GoodsDataUserExample;
import com.health.db.model.GoodsList;
import com.health.db.model.GoodsOrder;
import com.health.db.model.UserAccountJournal;
import com.health.db.model.UserAccountLedger;
import com.health.db.model.UserCardList;
import com.health.db.model.UserLIST;
import com.health.db.service.sm.IGoodsDataService;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;

public class GoodsDataServiceImpl implements IGoodsDataService {
 
	
	private IGoodsDataDao goodsDataDao;
	
	private IGoodsDataUserDao goodsDataUserDao;
	
	private IUserCardListDao userCardListDao;
	
	private IUserLISTDao userLISTDao;
	
	private IGoodsListDao goodsListDao ;
	
	private IGoodsOrderDao goodsOrderDao ;
	
	private IUserAccountJournalDao userAccountJournalDao ;
	
	private IUserAccountLedgerDao userAccountLedgerDao ;
	
	private IGoodsDataStuffRemarkDao goodsDataStuffRemarkDao;
	
	
	
	
	public IUserAccountLedgerDao getUserAccountLedgerDao() {
		return userAccountLedgerDao;
	}

	public void setUserAccountLedgerDao(IUserAccountLedgerDao userAccountLedgerDao) {
		this.userAccountLedgerDao = userAccountLedgerDao;
	}

	public IGoodsDataStuffRemarkDao getGoodsDataStuffRemarkDao() {
		return goodsDataStuffRemarkDao;
	}

	public void setGoodsDataStuffRemarkDao(
			IGoodsDataStuffRemarkDao goodsDataStuffRemarkDao) {
		this.goodsDataStuffRemarkDao = goodsDataStuffRemarkDao;
	}

	public IUserAccountJournalDao getUserAccountJournalDao() {
		return userAccountJournalDao;
	}

	public void setUserAccountJournalDao(
			IUserAccountJournalDao userAccountJournalDao) {
		this.userAccountJournalDao = userAccountJournalDao;
	}

	public IGoodsOrderDao getGoodsOrderDao() {
		return goodsOrderDao;
	}

	public void setGoodsOrderDao(IGoodsOrderDao goodsOrderDao) {
		this.goodsOrderDao = goodsOrderDao;
	}

	public IGoodsListDao getGoodsListDao() {
		return goodsListDao;
	}

	public void setGoodsListDao(IGoodsListDao goodsListDao) {
		this.goodsListDao = goodsListDao;
	}

	public IUserLISTDao getUserLISTDao() {
		return userLISTDao;
	}

	public void setUserLISTDao(IUserLISTDao userLISTDao) {
		this.userLISTDao = userLISTDao;
	}

	public IUserCardListDao getUserCardListDao() {
		return userCardListDao;
	}

	public void setUserCardListDao(IUserCardListDao userCardListDao) {
		this.userCardListDao = userCardListDao;
	}

	public IGoodsDataDao getGoodsDataDao() {
		return goodsDataDao;
	}

	public void setGoodsDataDao(IGoodsDataDao goodsDataDao) {
		this.goodsDataDao = goodsDataDao;
	}


	public IGoodsDataUserDao getGoodsDataUserDao() {
		return goodsDataUserDao;
	}

	public void setGoodsDataUserDao(IGoodsDataUserDao goodsDataUserDao) {
		this.goodsDataUserDao = goodsDataUserDao;
	}

	@Override
	public List<GoodsData> selectByExample(GoodsDataExample example) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int insertVIPGoodsList(GoodsOrder  record,String out_trade_no) {
		// TODO Auto-generated method stub
		//int returnFlag=-1;
		Long goodsId = record.getGoodsid();
		Long userId = record.getOwnerid();
		//GoodsDataExample example = new GoodsDataExample();
		//example.setGoodsid(record.getGoodsid());
		GoodsList goods = goodsListDao.selectGoodsAndDatasByGoodsId(goodsId);
		//查看下属产品列表
		List<GoodsData> goodsList = goods.getGoodsDataList();
		if (null==goods||null==goodsList) {
			return -2;
		}
	
		List<GoodsDataUser> list = new ArrayList<GoodsDataUser>();
		Date now =DateUtils.now();
		UserLIST userLIST= userLISTDao.selectByUserId(record.getOwnerid());
		if (null!=userLIST.getVipLevel()&&null!=userLIST.getVipEndDate()) {
			
			if (userLIST.getVipEndDate().compareTo(DateUtils.now())>0) {
				now = userLIST.getVipEndDate();
			}
		}
		
		for (int i = 0; i < goodsList.size(); i++) {
			
			GoodsData goodsDataTemp = goodsList.get(i);

		    String validDuration= goodsDataTemp.getValidDuration();

		    String frequency = goodsDataTemp.getFrequency();
		    
			
			Byte rechargeFlag = goodsDataTemp.getRechargeFlag();
			
			if (null!=rechargeFlag&&rechargeFlag.intValue()==1) {
				UserCardList userCardList =activeUserCardByRecharge( goodsDataTemp , userId, goodsId ) ;
				userCardListDao.insertNoCardId(userCardList);
				
			}else if (StringUtils.isNotBlank(validDuration)&&StringUtils.isNotBlank(frequency)
				&&	!validDuration.equals(frequency)) 
			{
				int validDurationInt= Integer.valueOf(validDuration);
				int frequencyInt= Integer.valueOf(frequency);
				
				do {
					
					GoodsDataUser goodsDataListTemp =new GoodsDataUser();
					goodsDataListTemp.setItemValue(goodsDataTemp.getItemValue());
					goodsDataListTemp.setItemName(goodsDataTemp.getItemName());
					goodsDataListTemp.setGoodsid(goodsId);
					goodsDataListTemp.setOwnerId(userId);
					goodsDataListTemp.setUpdateDate(now);
					goodsDataListTemp.setGoodsDataId(goodsDataTemp.getRecid());
					goodsDataListTemp.setFailureDate(DateUtils.getMonthAfter(now, frequencyInt));
					goodsDataListTemp.setActivateDate(DateUtils.getMonthAfter(goodsDataListTemp.getFailureDate(), -Integer.valueOf(frequency)));
					goodsDataListTemp.setOwnerName(userLIST.getUserName());
					goodsDataListTemp.setOperFlag((byte) 0);
					frequencyInt=frequencyInt+Integer.valueOf(frequency);
					list.add(goodsDataListTemp);
					
				} while (frequencyInt<=validDurationInt);
				
			}else{
				
				GoodsDataUser goodsDataListTemp =new GoodsDataUser();
				goodsDataListTemp.setItemValue(goodsDataTemp.getItemValue());
				goodsDataListTemp.setItemName(goodsDataListTemp.getItemName());
				goodsDataListTemp.setGoodsid(goodsId);
				goodsDataListTemp.setOwnerId(userId);
				goodsDataListTemp.setUpdateDate(now);
				goodsDataListTemp.setGoodsDataId(goodsDataTemp.getRecid());
				goodsDataListTemp.setOwnerName(userLIST.getUserName());
				if (StringUtils.isNotBlank(validDuration)) {
					goodsDataListTemp.setFailureDate(DateUtils.getMonthAfter(now, Integer.valueOf(validDuration)));
					goodsDataListTemp.setActivateDate(now);
				}else{
					goodsDataListTemp.setFailureDate(DateUtils.getMonthAfter(now, 12));
					goodsDataListTemp.setActivateDate(now);
				}
				goodsDataListTemp.setOperFlag((byte) 0);
				list.add(goodsDataListTemp);
			}
		}
		
		userLIST.setVipLevel(goods.getLevel());
		userLIST.setVipStartDate(null==userLIST.getVipStartDate()?DateUtils.now():userLIST.getVipStartDate());
		userLIST.setVipEndDate(DateUtils.getMonthAfter(now, Integer.valueOf(goodsList.get(0).getValidDuration())));
			
		UserAccountJournal userAccountJournal	=delayUpdateUserAccountJournal(out_trade_no,record, record.getOwnerid(), null);
		goodsOrderDao.update(record);
		userAccountJournalDao.insert(userAccountJournal);
		goodsDataUserDao.insertBatch(list);
		userLISTDao.updateByPrimaryKey(userLIST);
		return 1;
		
	}
	
	/**
	 * 新生成动态卡号
	 * @param goodsDataTemp
	 * @param userId
	 * @param cardTypeId
	 * @return
	 */
	public UserCardList activeUserCardByRecharge(GoodsData goodsDataTemp ,Long userId,Long cardTypeId ) {
		// TODO Auto-generated method stub
		
		UserCardList userCardList = new UserCardList();
		
		//卡资源表中的数据迁移
		int x=(int)(Math.random()*100);
		if (x<10) {
			userCardList.setCardIdno("VIP"+String.valueOf(DateUtils.millis())+"0"+String.valueOf(x));
		}else{
			userCardList.setCardIdno("VIP"+String.valueOf(DateUtils.millis())+String.valueOf(x));	
		}
		
		userCardList.setCardtypeid(cardTypeId.intValue());
		userCardList.setCardName(goodsDataTemp.getItemName());
		userCardList.setOwnerid(userId);
		userCardList.setPassword("");
		userCardList.setIsUsedFlag((short)1);
		//自动生成
		userCardList.setComment("1");
		//卡类型表中的数据迁移
		userCardList.setCardtime02(new BigDecimal( goodsDataTemp.getItemValue()));
		userCardList.setLefttime02(new BigDecimal(goodsDataTemp.getItemValue()));
		
		Date now = DateUtils.now();
		userCardList.setActivateDate(now);
		//多少天后失效
		userCardList.setFailureDate(DateUtils.getMonthAfter(now, Integer.valueOf(goodsDataTemp.getValidDuration())));
		//时间
		userCardList.setCreateDate(now);
		userCardList.setUpdateDate(now);
		
		return userCardList;
	}
	
	
	/**
	 * 延时处理更新user表
	 * 支付回调调用
	 * accountJournal 用户记录
	 */
	private UserAccountJournal delayUpdateUserAccountJournal(String out_trade_no,GoodsOrder  record,
			long userId, UserAccountLedger accountLedger) {

		
			UserAccountJournal accountJournal = new UserAccountJournal();
			//支付成功
			if (record.getPayTypeId()==Constant.CONSTANTS_PAYMENT_WEIXIN) {
				accountJournal.setJournalDesc(Constant.CONSTANTS_VOUCHERNAME_2 +"-"+Constant.CONSTANTS_VOUCHERNAME_51+"订单号"+out_trade_no);
				accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_51+"-"+Constant.CONSTANTS_VOUCHERNAME_2 );
			}else if(record.getPayTypeId()==Constant.CONSTANTS_PAYMENT_ALIPAY){
				accountJournal.setJournalDesc(Constant.CONSTANTS_VOUCHERNAME_4 +"-"+Constant.CONSTANTS_VOUCHERNAME_51+"订单号"+out_trade_no);
				accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_51+"-"+Constant.CONSTANTS_VOUCHERNAME_4 );
			}
			
			//获取商品类型
			if (StringUtils.isNotBlank(record.getGoodsType())) {
				accountJournal.setSourceid(Integer.valueOf(record.getGoodsType()));
			}
		
			//商户订单号 作为备注
			accountJournal.setComment(out_trade_no);
			// 查看用户表相关信息
			//Long docId = userId;
			UserLIST userLIST = userLISTDao.selectByUserId(userId);

			// 账单日志表
			//日记账记录
			if (null!=accountLedger) {
				accountJournal.setAcctpageid(accountLedger.getAcctpageid());
			}
			
			accountJournal.setAccountid(userId);
			accountJournal.setAccountIdno(userLIST.getUserNo());
			accountJournal.setAccountName(userLIST.getUserName());
			accountJournal.setVoucherid(record.getRecid().toString());
			accountJournal.setJournalTotal(record.getTotal());
			accountJournal.setCreateUserid(userId);
			accountJournal.setUpdateUserid(userId);
			accountJournal.setVoucherDate(record.getCreateDate());
			//充值
			accountJournal.setVouchertypeid(51);

			return accountJournal;
		}

	/**
	 * 查询单条详情
	 */
	@Override
	public GoodsDataUser selectGoodsDataUser(Long recid) {
		// TODO Auto-generated method stub
		return goodsDataUserDao.selectDetialByPrimaryKey(recid);
	}
	
	
	/**
	 * 查询单条详情
	 */
	@Override
	public GoodsDataUser selectSimpleGoodsDataUser(Long recid) {
		// TODO Auto-generated method stub
		return goodsDataUserDao.selectSimpleGoodsDataUser(recid);
	}

	/**
	 * flag :0 recId=recId  
	 * flag :1 recId=userId/ownerId
	 * flag :2 recId=acceptId  
	 */
	@Override
	public List<GoodsDataUser> selectGoodsDataUserList(GoodsDataUserExample example,Long recId) {
		// TODO Auto-generated method stub
		
		 List<GoodsDataUser> list = new ArrayList<GoodsDataUser>();
		if (null==example) {
			list.add(goodsDataUserDao.selectDetialByPrimaryKey(recId));
		}else {
			list= goodsDataUserDao.selectByExample(example);
		}
		return list;
	}
	
	/**
	 * 更新recordList
	 */
	@Override
	public int updateGoodsDataUser(GoodsDataUser dataUser,
			List<GoodsDataStuffRemark> list) {
		// TODO Auto-generated method stub
		int exectNum=goodsDataUserDao.updateByPrimaryKeySelective(dataUser);
		
		if (exectNum==1&&null!=list&&list.size()>0) {
			//先删除过期的数据
			goodsDataStuffRemarkDao.deleteByUserDataId(dataUser.getRecid());
			goodsDataStuffRemarkDao.insertBatch(list);
		}
		
		return exectNum;
	}
	
	
	/**
	 * 更新recordList
	 */
	@Override
	public int updateGoodsDataUserAccept(GoodsDataUser dataUser) {
		// TODO Auto-generated method stub
		
		GoodsDataUser currGoodsDataUser = goodsDataUserDao.selectSimpleGoodsDataUser(dataUser.getRecid());
		
		if (currGoodsDataUser.getOperFlag().intValue()==Constant.CONSTANTS_HEALTH_RECORD_RUNSTATUS_ID_2.intValue()) {
			return goodsDataUserDao.updateByPrimaryKeySelective(dataUser);
		}else{
			return -2;
		}	
	}
	
	
	@Override
	public int updateGoodsDataUserFinish(GoodsDataUser dataUser,
									UserAccountLedger userAccountLedger, int type,GoodsDataUser currdataUser) {

		   int exectNum=goodsDataUserDao.updateByPrimaryKeySelective(dataUser);
			if (type==Constant.CONSTANTS_ACCOUNT_EXIST_TYPE_0) {
				userAccountLedgerDao.insertAccountLedger(userAccountLedger);
			}else{
				userAccountLedgerDao.updateBalance(userAccountLedger);
			}
			
			delayUpdateDocAccountJournal(currdataUser, userAccountLedger);
			return exectNum;
	}
	
	
	/**
	 * 延时处理更新doc表
	 */
	private void delayUpdateDocAccountJournal(GoodsDataUser dataUser, UserAccountLedger accountLedger) {

			// 查看用户表相关信息
			Long userId = dataUser.getAccepterId();
			UserLIST userLIST = userLISTDao.selectByUserId(userId);

			// 账单日志表
			//日记账记录
			UserAccountJournal accountJournal = new UserAccountJournal();
			accountJournal.setJournalDesc(dataUser.getItemName());
			accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_52);
			
			accountJournal.setAcctpageid(accountLedger.getAcctpageid());
			accountJournal.setAccountid(userId);
			accountJournal.setAccountIdno(userLIST.getUserNo());
			accountJournal.setAccountName(userLIST.getUserName());
			accountJournal.setVoucherid(dataUser.getRecid().toString());
			//accountJournal.setVoucherIdno(orderInfoTemp.getRegisterNo());
			//accountJournal.setJournalDesc(orderInfoTemp.getUserName()+ orderInfoTemp.getOrderTypeDesc());
			//accountJournal.setVoucherName(Constant.CONSTANTS_VOUCHERNAME_1);
			accountJournal.setJournalTotal(dataUser.getRegisterPayoffTotal());
			accountJournal.setCreateUserid(userId);
			accountJournal.setUpdateUserid(userId);
			accountJournal.setVoucherDate(dataUser.getUpdateDate());
			accountJournal.setVouchertypeid(52);

			userAccountJournalDao.insert(accountJournal);
		}
	
	
	

	
}
